#include "receiver_thread.h"
#include <boost/lambda/lambda.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <string.h>

using namespace boost::lambda;
using namespace boost;
using namespace std;

void start_tag(void *user_data, const XML_Char *name, const XML_Char **atts)
{
	receiver_thread *r = (receiver_thread*) user_data;

	string tag(name);

	list<string> attrib;
	for(int i = 0; atts[i]; ++i) {
		attrib.push_back(string(atts[i]));
	}
	r->dispatch(name, attrib);
}

void receiver_thread::start()
{
	_thrd.reset(
		new boost::thread(bind(&receiver_thread::run, this)));
	_parser = XML_ParserCreate(NULL);
	if(!XML_Parse(_parser, "<stream>", 8, false)) {
		cout << "error, oO" << endl;
	}
	XML_SetUserData(_parser, (void*)this);
	XML_SetStartElementHandler(_parser, &start_tag);
}

void receiver_thread::run()
{
	XML_Status status;
	string str;
	while(true) {
		if(is_interrupted()) {
			return;
		}
		str += _sock->read();
		status = XML_Parse(_parser, str.c_str(), str.size(),
					 str.size() == 0);
		if(status == XML_STATUS_ERROR) {
			/* handle error */
			cout << "error in parsing..." << endl;
		} else {
			str = "";
		}
	}
}

void receiver_thread::dispatch(const string &tag, const list<string> &attr)
{
	if(tag == "play") {
		// search title...
		string file;
		for(list<string>::const_iterator i = attr.begin(); 
		    i != attr.end(); ++i) {
			if((*i) == "file") {
				file = *(++i);
				break;
			}
		}
		boost::shared_ptr<title> t(new title("", file, 0));
		boost::shared_ptr<message> m(
			new play_message(t));
		_queue->put(m);
	} else if(tag == "pause") {
		boost::shared_ptr<message> m(
			new message(message::PAUSE));
		_queue->put(m);
	} else if(tag == "list") {
		boost::shared_ptr<message> m(
			new message(message::LIST));
		_queue->put(m);
	}
}

